package com.tanhua.server.service;

import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
@Slf4j
public class VoiceService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Reference
    private VoiceApi voiceApi;

    public void sendVoice(MultipartFile soundFile) throws IOException {
        // 1. 获取当前用户的信息
        Long userId = UserHolder.getUserId();// 当前用户id


        String VoiceKey="sendVoiceRedisKey_"+userId;
        Integer sendVoiceTimes =2;// 初始化发送语音次数
        Integer times =(Integer) redisTemplate.opsForValue().get(VoiceKey);

        // 2. 先判断是否有已存在键,如果没有,在redis里增加一条数据 默认上传次数为三次
        if (times==null){
            times=sendVoiceTimes;
            redisTemplate.opsForValue().set(VoiceKey,times);

        }else {
            redisTemplate.opsForValue().set(VoiceKey,(times-1));
        }

        // 如果说次数少于三次 提醒一下
        if (times<= 0){
            throw new TanHuaException("当日发送语音次数不足,请第二天再尝试~");
        }
        String soundUrl = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
        // 3. 使用springboot的@scheduled来定时 每天凌晨12点清空数据

        // 4. 调用接口服务 保存语音到MongoDB数据库表
        voiceApi.sendVoice(userId,soundUrl);

    }


}
